package com.cobra.framework;
import com.cobra.framework.protocol.http.HttpClient;
import com.cobra.framework.protocol.http.HttpProtocol;
import com.cobra.framework.register.RemoteMapRegister;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.List;

public class ProxyFactory<T> {

    @SuppressWarnings("unchecked")
    public static <T> T getProxy(final Class interfaceClass) {
        return (T)Proxy.newProxyInstance(interfaceClass.getClassLoader(), new Class[]{interfaceClass}, new InvocationHandler() {
          //这里是对方法的代理执行,获取将参数序列化传输，在接受方接受到参数之后根据参数的信息找到对应的实现类进行实现。
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    //代理逻辑
                Invocation invocation = new Invocation(
                interfaceClass.getName(),method.getName(),method.getParameterTypes()
                ,args
                );
                List<URL> urlList = RemoteMapRegister.get(interfaceClass.getName());
                System.out.println(urlList);
                Protocol protocol =ProtocolFactory.getProtocol();
                URL url = LoadBalance.random(urlList);
                String hostname = url.getHostname();
                Integer port = url.getPort();
                System.out.println(String.format("调用 主机 %s 端口 %s 的服务",hostname,port));
                String result = protocol.send(url, invocation);
                return result;
            }
        });
    }
}
